package kyssion.leetcode.num151_200;

public class code152_乘积最大子序列 {
    public static void main(String[] args) {
        System.out.println(new code152_乘积最大子序列().maxProduct(
                new int[]{
                        2,3,-2,4,3,4,5,4,-18,-3,2,-2,-1,2,-3,4,-3,2
                }
        ));
    }

    /**
     * 注意一个点,就是可能会发生负数乘负数导致结果有问题
     * @param nums
     * @return
     */
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int[] other = new int[nums.length];
        int max = nums[0];
        if (nums[0] < 0) {
            other[0] = nums[0];
            nums[0] = 0;
        }
        for (int a = 1; a < nums.length; a++) {
            if (nums[a] > 0) {
                other[a] = Math.min(0, nums[a] * other[a - 1]);
                nums[a] = Math.max(nums[a], nums[a - 1] * nums[a]);
            } else {
                other[a] = Math.min(nums[a], nums[a - 1] * nums[a]);
                nums[a] = Math.max(0, other[a - 1] * nums[a]);
            }
            max = Math.max(nums[a], max);
        }
        return max;
    }
}
